import asyncio
import websockets
import subprocess
import os
import signal
import time

# 用于存储当前的子进程
current_process = None

# 启动 Python 进程
def start_process(resolution, frameRate):
    global current_process
    # 假设要启动的 Python 脚本路径是 "your_script.py"，并传递 resolution 参数
    command = ['python3', './publisher.py', resolution, frameRate]
    current_process = subprocess.Popen(command)
    print(f"Started process with resolution: {resolution, frameRate}")

# 终止当前的子进程
def stop_process():
    global current_process
    if current_process:
        print("Killing current process...")
        current_process.terminate()  # 终止进程
        current_process.wait()  # 等待进程退出
        print("Process terminated.")
        current_process = None

# WebSocket 客户端，接收并解析命令
async def receive_commands(uri):
    async with websockets.connect(uri) as websocket:
        print("Connected as command_receiver")

        try:
            while True:
                command = await websocket.recv()
                # 解析命令
                # recive websocket
                # video|1920x1080|30
                if command.startswith("video|"):
                    pre, resolution, frameRate = command.split("|")
                    print(f"Received resolution change command: {resolution, frameRate}")
  
                    # 停止原有进程并启动新进程
                    if current_process:
                        stop_process()
                        # TODO 需要Debug
                    time.sleep(60)
                    start_process(resolution, frameRate)

        except websockets.exceptions.ConnectionClosed:
            print("Connection closed")

# 主程序
async def main():
    start_process("1280x720", "30")
    uri = "ws://39.106.77.250:8089/ws?command_receiver"
    await receive_commands(uri)

if __name__ == "__main__":
    asyncio.run(main())
